using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;

namespace VisualmodBep.Helper;

public class AllInstance<Tp> where Tp : class
{
    public static readonly List<Tp> AllInstances = new List<Tp>();

    protected void InstanceAdd(Tp that)
    {
        if (!AllInstances.Contains(that))
        {
            AllInstances.Add(that); // add to collection
        }
    }
}

// call ctor: base(typeof(Setter))
public class ClassPropertyGetter
{
    public ClassPropertyGetter(Type Class, StringComparison compare = StringComparison.OrdinalIgnoreCase, bool showError = true)
    {
        this._class = Class;
        this._compare = compare;
        this._showError = showError;
        this.props = Class.GetProperties();
    }

    private bool _showError;
    private StringComparison _compare;
    private Type _class;
    private readonly PropertyInfo[] props;

    public PropertyInfo GetProperty(string name)
    {
        return GetProperty(name, _compare, _showError);
    }

    public PropertyInfo GetProperty(string name, StringComparison compare, bool showError)
    {
        foreach (PropertyInfo prop in props)
        {
            if (prop.Name.Equals(name, compare))
            {
                return prop;
            }
        }
        if (showError)
        {
            Log.LogError($"ClassPropertyGetter \"{_class.FullName}.{name}\" not found");
        }
        return null;
    }

    public PropertyInfo[] GetProperties()
    {
        return props;
    }
}

public class Xml
{
    public static List<T> LoadXml<T>(string filePath, string searchPattern = "*.xml") where T : class, new()
    {
        if (!Directory.Exists(filePath))
        {
            Log.LogError($"Xml LoadXml \"{filePath}\" not exists.");
            return new List<T>();
        }
        string[] files = Directory.GetFiles(filePath, searchPattern);
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        List<T> result = new List<T>();

        Log.LogInfo($"Xml LoadXml {files.Length} files");
        foreach (string fileName in files)
        {
            Stream reader = new FileStream(fileName, FileMode.Open);
            T file = xmlSerializer.Deserialize(reader) as T;
            if (file == null)
            {
                Log.LogError($"  parsing error: {fileName}.");
                continue;
            }
            result.Add(file);
        }
        return result;
    }
}
